package cn.swust.score.controller;
 
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException; 
import java.util.List; 
import javax.imageio.ImageIO; 
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;  
   
import cn.swust.score.service.GradeService;

import org.springframework.beans.BeanUtils; 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated; 
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; 
import cn.swust.score.basepojo.ResultResponse;
import cn.swust.score.pojo.Candidate; 
import cn.swust.score.pojo.CurrCandidateInfo;
import cn.swust.score.pojo.Grade;
import cn.swust.score.pojo.NextCandidate;
import cn.swust.score.service.CandidateService;
import io.swagger.annotations.Api; 
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam; 
import  cn.swust.score.service.CandidateStagInfoService;
import cn.swust.score.service.GradeAdminService;
import cn.swust.score.service.RaterService; 

@Api(tags = "评分人评分")
@RestController
@Validated
@RequestMapping("/grade")
public class GradeController extends BaseController {
	
	@Autowired
	public CandidateService candidateService;
	
	@Autowired
	public GradeAdminService GrageService;
	
	@Autowired
	public RaterService raterService;
	
	
	public static class NextInfo{
		Integer scoreInfoId;
		Integer sort;
		Integer stageId;
		public Integer getScoreInfoId() {
			return scoreInfoId;
		}
		public void setScoreInfoId(Integer scoreInfoId) {
			this.scoreInfoId = scoreInfoId;
		}
		public Integer getSort() {
			return sort;
		}
		public void setSort(Integer sort) {
			this.sort = sort;
		}
		public Integer getStageId() {
			return stageId;
		}
		public void setStageId(Integer stageId) {
			this.stageId = stageId;
		}  
	} 
	@PreAuthorize("hasAuthority('RATER')")
	@ApiOperation(value = "获取下一个评分人") 
	@PostMapping("/next") 
	public ResultResponse<Object> getNextCandidate(
			@ApiParam(required = true, value = "比赛信息")
			@Valid @RequestBody  NextInfo into
			 ) {
		Candidate candidate = candidateService.getNext(into.getScoreInfoId(), into.getSort()+1);
	  	if (candidate == null){
	  		CurrCandidateInfo info = new CurrCandidateInfo();
	  		info.setCurrStageId(into.getStageId() +1);
	  		info.setCurrCandidateSort(0);
	  		info.setId(this.getRateId());
	  		raterService.setCurrCandidate(info);
	  		return new ResultResponse<Object> (0,"OK", "");
	  	} 
		Grade grade = candidateService.getByCIdRIdSId(candidate.getId(),into.getStageId(), this.getRateId());
	   	if (grade == null)
	  	{ 
	  		return new ResultResponse<Object>(candidate);
	  	}else	{  		
	  		NextCandidate c = new NextCandidate();
	   		BeanUtils.copyProperties(candidate, c);
	   		c.setFraction(grade.getFraction());
	  		return new ResultResponse<Object>(c);
	  	}
	}
	@PreAuthorize("hasAuthority('RATER')")
	@ApiOperation(value = "打分，增加和修改")
	@PostMapping("/set")
	public ResultResponse<Grade> set (
			@ApiParam(required = true, value = "评分信息")
			@Valid @RequestBody Grade grad) {
		if(grad.getFraction() == null)
			grad.setFraction(0);
		Candidate c = candidateService.getById(grad.getCandidateId());
		int code = 0;
		String msg="";
		if (c!= null)
		{
		int re = candidateService.setScore(grad.getCandidateId(),
				this.getRateId(),grad.getStageId(),grad.getFraction());
		
		grad.setSort(c.getSort());
		grad.setCandidateId(c.id);
		
		switch (re){
			case 1: //"新增成功";
				code = 0;
				msg = "新增成功";
				break;
			case  2://"新增失败";
				code = 1;
				msg = "新增失败";
				break;
			case 3://"修改成功";
				code = 0;
				msg = "修改成功";
				break;
			case 4://"修改失败";
				code = 1;
				msg = "修改失败";
				break;
			case 5://"成绩已经确认不能修改";
				code = 1;
				msg = "成绩已经确认不能修改";
				break;
			case 6://"评分人和候选人学校相同，拒绝评分"
				code = 1;
				msg = "评分人和候选人学校相同，拒绝评分";
				break;
		}
		}else
		{
			code = 7;
			msg = "候选人不存在！";
		}
		return new ResultResponse<Grade>(code,msg,grad);
	}
	public static class allInfo{
		Integer stageId;

		public Integer getStageId() {
			return stageId;
		}

		public void setStageId(Integer stageId) {
			this.stageId = stageId;
		}
		
	}
	@PreAuthorize("hasAuthority('RATER')")
	@ApiOperation(value = "获取本人打分信息")
	@PostMapping("/getall")
	public ResultResponse<List<Grade>>getAllGrade(
			@ApiParam(required = true, value = "打分信息 //阶段信息")
			@Valid @RequestBody  allInfo info) { 
		return new ResultResponse<List<Grade>>(candidateService.listByRaterId( 
				this.getRateId(), info.getStageId(), this.getRateSchool()));
	}


	@Autowired
	GradeService gradeService;
	@Autowired
	CandidateStagInfoService candidateStagInfoService;
	
	@PreAuthorize("hasAuthority('RATER')")
	@ApiOperation(value = "确认提交")
	@PostMapping("/commit")
	public ResultResponse<String> commite(@ApiParam(required = true, value = "评分阶段")
	@Valid @RequestBody allInfo info) {
		 if (candidateStagInfoService.commitRaterScore(info.getStageId(),
				 this.getRateId()) != 0)
		 {
			 return new ResultResponse<String>(1,"成绩没有提交完毕",null);
		 }else

		return new ResultResponse<String>(0,"OK",null);
	} 
	@PreAuthorize("hasAuthority('RATER')")
	@ApiOperation(value = "获取当前打分阶段及打分顺序")
	@PostMapping("/curr/get")
	public ResultResponse<CurrCandidateInfo> getCandidate( ) { 
		Integer id  = this.getRateId();
		CurrCandidateInfo info = raterService.getCurrCandidate(id);
		
		return new ResultResponse<CurrCandidateInfo>(0,"OK",info);
	} 
	
	@Value("${files.path}")
	private String filesPath;
	@PreAuthorize("hasAuthority('RATER')")
	@ApiOperation(value = "获取照片")
	@RequestMapping(value = "/getimg", method = RequestMethod.GET, produces = { MediaType.IMAGE_PNG_VALUE,
			MediaType.IMAGE_JPEG_VALUE })
	public byte[] getImage(@ApiParam(required = true, value = "查询候选人编号") Integer id,
			HttpServletResponse response) throws IOException {

		Candidate c = candidateService.getById(id);
		if (c == null)
			return null;

		File file1 = null, file2 = null; 

		file1 = new File(filesPath + "/" + c.getPhone() + ".jpg");
		file2 = new File(filesPath + "/" + c.getPhone() + ".png");

		if (file1 == null & file2 == null)
			return null;
		ByteArrayOutputStream bao = new ByteArrayOutputStream();
		try {
			BufferedImage img = ImageIO.read(file1);
			ImageIO.write(img, "jpg", bao);
			return bao.toByteArray();
		} catch (IOException e) {
			BufferedImage img = ImageIO.read(file2);
			ImageIO.write(img, "png", bao);
			return bao.toByteArray();
		}  
	}
}
	
		
//		
//		public ResultResponse<List<StageGrade> > commite(@ApiParam(required = true, value = "评分阶段")
//	@Valid @RequestBody Integer stageId) {
//		//设置 确认
//		//计算得分，排名 candidate_stag_info
//		int raterId=this.getRateId();
//		List<StageGrade> candidateStagInfos=gradeService.commitService(raterId,stageId);
//		return new ResultResponse<List<StageGrade>>(0,"OK",candidateStagInfos);
// 
//	} 

